package base.web.controller;

import base.pojo.UserFile;
import base.service.ISystemDictionaryService;
import base.service.IUserFileService;
import common.RequireLogin;
import common.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import util.UploadUtil;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller@Scope("prototype")
public class UserFileController
{
    @Autowired
    IUserFileService iUserFileService;
    @Autowired
    ServletContext servletContext;
    @Autowired
    ISystemDictionaryService iSystemDictionaryService;

    @RequireLogin
    @RequestMapping("userFile.html")
    public String userFileIndex(Model model, HttpServletRequest request)
    {
        List<UserFile> list = iUserFileService.listUnTypeFiles();
        if(list.size()>0)
        {
            model.addAttribute("userFiles",list);
            model.addAttribute("fileTypes",iSystemDictionaryService.allSystemDictionaryItemBySn("userFileType"));
            return "userFiles_commit";
        }
        model.addAttribute("sessionId",request.getSession().getId());
        list = iUserFileService.listTypeFiles();
        model.addAttribute("userFiles",list);
        return "userFiles";
    }
    @RequestMapping("userFileUpload")
    @ResponseBody
    public void userFileUpload(MultipartFile file)
    {
        String basePath = servletContext.getRealPath("/upload") ;
        String fileName = UploadUtil.upload(file,basePath)      ;
        fileName        = "/upload/"+fileName                   ;
        iUserFileService.apply(fileName);
    }
    @RequestMapping("userFileSelectType.do")
    @ResponseBody
    public ServerResponse userFileSelectType(Long[] id,Long[] fileType)
    {
        return iUserFileService.userFileSelectType(id,fileType);
    }

}
